//
//  CloverConfigManager.m
//  DevSpoof
//
//  Created by huang on 2018/11/7.
//  Copyright © 2018年 wdys. All rights reserved.
//

#import "CloverConfigManager.h"

@interface CloverConfigManager()
@property (nonatomic, readwrite)BOOL hasMountEFI;
@end
@implementation CloverConfigManager
+ (instancetype)shared{
    static id _instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self class] new];
    });
    return _instance;
}
- (NSString *)configPath{
    return @"/Volumes/EFI/EFI/CLOVER/config.plist";
}
- (void)mountEFIPartition{
    NSString *filepath = [[NSBundle mainBundle] pathForResource:@"MountEFI" ofType:@"sh"];
    [NSTask launchedTaskWithLaunchPath:filepath arguments:@[]];
    self.hasMountEFI = YES;
}
- (NSMutableDictionary *)getCloverConfig{
    if (!self.hasMountEFI) {
        [[self class] mountEFIPartition];
    };
    return [NSMutableDictionary dictionaryWithContentsOfFile:self.configPath];
}
- (ConfigInfo *)currentHardwareInfo{
    ConfigInfo *info = [ConfigInfo new];
    NSDictionary *config = [self getCloverConfig];
    NSDictionary *SMBIOS = config[@"SMBIOS"];
    NSDictionary *RtVariables = config[@"RtVariables"];
    info.rom = RtVariables[@"ROM"];
    info.mbl = RtVariables[@"MLB"];
    info.smuuid = SMBIOS[@"SmUUID"];
    info.serialNumber = SMBIOS[@"SerialNumber"];
    return info;
}
- (ConfigInfo *)changeHardwareInfo{
    ConfigInfo *info = [ConfigInfo generateNew];
    NSMutableDictionary *config = [self getCloverConfig];
    NSMutableDictionary *SMBIOS = [config[@"SMBIOS"] mutableCopy];
    NSMutableDictionary *RtVariables = [config[@"RtVariables"] mutableCopy];
    RtVariables[@"ROM"] = info.rom;
    RtVariables[@"MLB"] = info.mbl;
    SMBIOS[@"SmUUID"] = info.smuuid;
    SMBIOS[@"SerialNumber"] = info.serialNumber;
    SMBIOS[@"BoardSerialNumber"] = info.mbl;
    config[@"SMBIOS"] = SMBIOS;
    config[@"RtVariables"] = RtVariables;
    [config writeToFile:self.configPath atomically:YES];
    return info;
}
@end
